<template lang="pug">
  h4 版面 | Foramt
  format-gallery
  format-preview(:format="formData")
  <!-- format-preview(:format="mockFormat") -->

  form(@submit.prevent="handleSubmit")
    input(type="text", v-model.trim="formData.name" placeholder="name")
    input(type="number", v-model="formData.width" placeholder="page width")
    input(type="number", v-model="formData.height" placeholder="page height")
    label {{ pageUnit}}
    br
    select(v-model="formData.suiteId")
      option(disabled, value="undefined") suites
      option(v-for="suite in suites" :key="suite.id" :value="suite.id") {{suite.name}}
    select(v-model="formData.backgroundColorId")
      option(disabled, value="undefined") bg colors
      option(v-for="color in colors" :key="color.id" :value="color.id") {{color.name}}
    button(@click.prevent="addElement") add element

    ul.elements-form-area
      li.element-list(v-for="(elem, idx) in formData.elements" :key="idx")
        div.thumbnail-icon(v-html="svgIcon(elem.compositionId)")
        select(v-model="formData.elements[idx].compositionId")
          option(disabled, value="undefined") compositions
          option(v-for="comp in compositions" :key="comp.id" :value="comp.id") {{comp.name}}
        select(v-model="formData.elements[idx].schemeId")
          option(disabled, value="undefined") schemes
          option(v-for="scheme in schemes.filter(s => (Object.keys(s.swatches).some(k => +k === elem.compositionId)))" :key="scheme.id" :value="scheme.id") {{scheme.name}}

        button(@click="removeElement(idx)" v-show="elements.length > 1") x

        br
        span {{ basedTip}}
        br
        select(v-model="elements[idx].size.key")
          option(disabled, value="undefined") size
          option(v-for="size in sizes" :key="size.id" :value="size.name") {{size.value}}
        input(type="number", v-model="elements[idx].size.value") 
        label {{ elemUnit}}


        br
        select(v-model="elements[idx].h.key")
          option(disabled, value="undefined") horizontal
          option(v-for="item in horizontals" :key="item.id" :value="item.name") {{item.value}}
        input(type="number", v-model="elements[idx].h.value")
        label {{ elemUnit}}

        br
        select(v-model="elements[idx].v.key")
          option(disabled, value="undefined") horizontal
          option(v-for="item in verticals" :key="item.id" :value="item.name") {{item.value}}
        input(type="number", v-model="elements[idx].v.value")
        label {{ elemUnit}}

    br
    button(type="submit" :disabled="submitDisabled") create format
    button(@click="resetFormData") Reset
</template>

<script setup>
import { computed, ref, onMounted, watch, inject } from 'vue';
import api from '../../apis/api'
import { checkFormData } from '../../utils/js.util'
import { sizes, horizontals, verticals } from './format-constants.js'
import FormatGallery from './format-gallery.vue'
import FormatPreview from './format-preview.vue'
import { mockFormat } from '../../utils/meregeFormatSvg.util'

const colors = inject('colors')
const graphics = inject('graphics')
const compositions = inject('compositions')
const schemes = inject('schemes')
const suites = inject('suites')
const formats = inject('formats')
const mainBrandId = inject('mainBrandId')

const elements = ref([{
  size: { key: 'width', value: 0 }, h: { key: 'left', value: 0 }, v: { key: 'top', value: 0 },
}])
const formData = ref({
  // name: undefined,
  name: 'a4',
  brandId: undefined,
  suiteId: undefined,
  width: 285,
  height: 210,
  // width: undefined,
  // height: undefined,
  backgroundColorId: undefined,
  elements: [{
    compositionId: undefined,
    schemeId: undefined,
  }],
})

watch(() => elements, elementList => {
  // sync formData
  elementList.value.map((elem, index) => {
    const { compositionId, schemeId } = formData.value.elements[index]
    formData.value.elements[index] = { compositionId, schemeId }

    const { size, h, v } = elem
    formData.value.elements[index][size.key] = size.value
    formData.value.elements[index][h.key] = h.value
    formData.value.elements[index][v.key] = v.value
  })
}, { deep: true })

const initialFormData = { ...formData.value, ...{ elements: [] } }
const handleSubmit = async () => {
  console.log(formData.value)
  const result = await api.post('formats', { ...formData.value })
  resetFormData()
};

const resetFormData = () => {
  for (let key in initialFormData) {
    formData.value[key] = initialFormData[key];
  }
};

const addElement = () => {
  elements.value.push({
    size: { key: 'width', value: 0 },
    h: { key: 'left', value: 0 },
    v: { key: 'top', value: 0 },
  })
  formData.value.elements.push({ compositionId: undefined, schemeId: undefined })
}

const removeElement = (index) => {
  elements.value = elements.value.filter((_, idx) => idx !== index)
  formData.value.elements = formData.value.elements.filter((_, idx) => idx !== index)
  console.log(elements.value)
  // console.log(id)

}
watch(mainBrandId, async () => {
  formData.value.brandId = mainBrandId.value
})
const submitDisabled = computed(() => !checkFormData(formData.value))
const pageUnit = computed(() => {
  const suite = suites?.value?.find(s => s.id === formData.value.suiteId)
  return suite ? suite.unit : 'px'
})
const elemUnit = computed(() => {
  const suite = suites?.value?.find(s => s.id === formData.value.suiteId)
  return suite ? (suite.usePercentSize ? '%' : suite.unit) : 'px'
})
const basedTip = computed(() => {
  const suite = suites?.value?.find(s => s.id === formData.value.suiteId)
  return suite ? (suite.usePercentSize ? 'Size percent based on ' + suite.based : 'Size Fixed') : 'size: '
})
const svgIcon = computed(() => (id => {
  const composition = compositions.value.find(item => item.id === id)
  return composition?.thumbnail || ''
}))

</script>
<style scoped>
.thumbnail-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 1.5rem;
  height: 1.5rem;
  cursor: pointer;
}

.thumbnail-icon svg {
  max-height: 1.5rem;
  max-width: 1.5rem;
}
</style>
